package com.zhongshengnetwork.rightbe.my.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
//import android.support.v4.app.ActivityCompat;
//import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.yalantis.ucrop.UCrop;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.QiniuUploadModel;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbservice.GroupUserdbService;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.QiniuModel;
import com.zhongshengnetwork.rightbe.common.QiniuCallBack;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.ContactUSActivity;
import com.zhongshengnetwork.rightbe.wzt.view.GlideEngine;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import me.iwf.photopicker.PhotoPicker;
//import me.iwf.photopicker.PhotoPickerActivity;
//import me.iwf.photopicker.utils.PhotoPickerIntent;

//三检查OK:2016-11-30
public class MyInfoActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private static final int TAKE_PICTURE = 1000;//拍照
    private static final int CHOOSE_PICTURE = 1001;//从相册选
    private static final int SELECT_LOCATION = 1002;//选择了位置
    private static final int CROP_PICTURE = 1003;//裁剪图片
    private static final int SCALE = 5;

    public static final int NICKNAME_REQUSET = 1;//昵称
    public static final int SIGN_REQUEST = 2;//签名

    private List<String> list=null;
    private List<String> groupkey=new ArrayList<String>();
    private ListView listview;
    private TopBarView topbar;
    private PublishSelectPicPopupWindow menuWindow;
    private List<String> itemList;
    private int imgType = 0;
    private MyAdapter adapter;
    private List<String> names;
    private boolean isChatFlag;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isChatFlag = getIntent().getBooleanExtra(APIKey.flagKey,false);
        itemList = new ArrayList<String>();
        itemList.add("拍一张");
        itemList.add("从相册选");
        itemList.add("取消");
        names = new ArrayList<String>();
        names.add("男");
        names.add("女");
        names.add("保密");
        names.add("取消");
        setContentView(R.layout.activity_my_info);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        listview=(ListView) findViewById(R.id.myinfo_listview);
        initData();
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
    }

    private void clickBack(){
        //更新群信息
        GroupUserdbService.updateGroupUserInfo(CustomApplication.loginModel.getUid(),CustomApplication.loginModel.getNickname(),CustomApplication.loginModel.getThumbheader());
        Bundle bundle = new Bundle();
        bundle.putString(APIKey.useridKey,CustomApplication.loginModel.getUid());
        bundle.putString(APIKey.nameKey,CustomApplication.loginModel.getNickname());
        bundle.putString(APIKey.headerKey,CustomApplication.loginModel.getThumbheader());
        Intent intent = new Intent();
        intent.putExtras(bundle);
        setResult(RESULT_OK,intent);
        finish();
    }

    //返回按键监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            clickBack();
        }

        return false;

    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        clickBack();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    public void initData(){
        list = new ArrayList<String>();
        groupkey.add("0组");
        list.add("0组");

        groupkey.add("A组");
        List<String> aList = new ArrayList<String>();
        aList.add("昵称");
        //aList.add("二维码");
        //aList.add("地址");
        list.add("A组");
        list.addAll(aList);

        groupkey.add("B组");
        List<String> bList = new ArrayList<String>();
        bList.add("性别");
        bList.add("地区");
        bList.add("个性签名");
        list.add("B组");
        list.addAll(bList);
    }

    private class MyAdapter extends BaseAdapter implements View.OnClickListener {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            if(groupkey.contains(getItem(position))){
                return false;
            }
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View view=convertView;
            if(groupkey.contains(getItem(position))){
                if (position == 0){
                    view= LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.my_info_list_header, null);
                    ImageView myInfoBg = (ImageView) view.findViewById(R.id.my_info_bg);
                    ImageView myInfoHeader = (ImageView) view.findViewById(R.id.my_info_header);
                    if (MyInfoActivity.this != null){
                        Glide.with(MyInfoActivity.this).load(CustomApplication.loginModel.getBackground()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(myInfoBg);
                        Glide.with(MyInfoActivity.this).load(CustomApplication.loginModel.getThumbheader()).transform(new CircleTransform(MyInfoActivity.this)).dontAnimate().into(myInfoHeader);
                    }
                    myInfoBg.setOnClickListener(this);
                    myInfoHeader.setOnClickListener(this);
                }else {
                    view= LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.my_list_heaer, null);
                    TextView text = (TextView) view.findViewById(R.id.my_list_header_text);
                    text.setText("");
                }
            }else{
                view=LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.my_info_list_item, null);
                TextView text = (TextView) view.findViewById(R.id.my_info_list_text);
                TextView detail = (TextView) view.findViewById(R.id.my_info_list_detail);
                TextView fullText = (TextView) view.findViewById(R.id.my_info_list_fulltext);
                ImageView next = (ImageView) view.findViewById(R.id.my_info_list_next);
                ImageView code = (ImageView) view.findViewById(R.id.my_info_list_code);
                text.setText((CharSequence) getItem(position));
                if (position == 2){//昵称
                    code.setVisibility(View.INVISIBLE);
                    detail.setText((CharSequence) CustomApplication.loginModel.getNickname());
               }else if (position == 4){//性别
                    code.setVisibility(View.INVISIBLE);
                    if (CustomApplication.loginModel.getSex().equals("0")){
                        detail.setText("保密");
                    }else if(CustomApplication.loginModel.getSex().equals("1")){
                        detail.setText("男");
                    }else {
                        detail.setText("女");
                    }

                }else if (position == 5){//地区
                    code.setVisibility(View.INVISIBLE);
                    detail.setText((CharSequence) CustomApplication.loginModel.getLocation());
                }else if (position == 6){//个性签名
                    code.setVisibility(View.INVISIBLE);
                    detail.setText((CharSequence) CustomApplication.loginModel.getSignature());
                }
                fullText.setTag(position);
                fullText.setOnClickListener(this);
            }
            return view;
        }

        // 监听事件实现
        public void onClick(View v) {
            if (v.getId() == R.id.my_info_bg){
                imgType = 0;
                //System.out.print("点击了背景图\n");
                menuWindow = new PublishSelectPicPopupWindow(MyInfoActivity.this,itemsOnClick,itemList);
                // 显示窗口
                menuWindow.showAtLocation(v,
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }else if (v.getId() == R.id.my_info_header){

                System.out.print("点击了头像\n");
                imgType = 1;
                menuWindow = new PublishSelectPicPopupWindow(MyInfoActivity.this,itemsOnClick,itemList);
                // 显示窗口
                menuWindow.showAtLocation(v,
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                //changeHeader();

            }else {
                int destination = (Integer) v.getTag();
                switch (destination) {
                    case 2://昵称
                        Intent intent = new Intent(MyInfoActivity.this,
                                EditActivity.class);
                        intent.putExtra("type",NICKNAME_REQUSET);
                        intent.putExtra("name",CustomApplication.loginModel.getNickname());
                        startActivityForResult(intent, NICKNAME_REQUSET);
                        break;
                    case 4://性别
                        imgType = 3;
                        menuWindow = new PublishSelectPicPopupWindow(MyInfoActivity.this,itemsOnClick,names);
                        // 显示窗口
                        menuWindow.showAtLocation(v,
                                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                        break;
                    case 5://地区
                        PermissionUtils.isLocationNote(MyInfoActivity.this, new PermissionCallback() {
                            @Override
                            public void onResult(boolean flag, boolean showAlert) {
                                if (flag == true){
                                    startActivityForResult(new Intent(MyInfoActivity.this, MyAreaActivity.class),SELECT_LOCATION);
                                }
                            }
                        });
                        break;
                    case 6://个性签名
                        Intent signIntent = new Intent(MyInfoActivity.this,
                                EditActivity.class);
                        signIntent.putExtra("type",SIGN_REQUEST);
                        signIntent.putExtra("name",CommonUtils.formatString(CustomApplication.loginModel.getSignature()));
                        startActivityForResult(signIntent, SIGN_REQUEST);
                        break;

                    default:
                        System.out.print("onClick\n");
                        break;
                }
            }

        }
    }



    /**拍照获取相片**/
    private void doTakePhoto() {
        PermissionUtils.showCamaraNote(MyInfoActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (PermissionUtils.cameraIsCanUse() == true){
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));//Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
                        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //直接使用，没有缩小
                        startActivityForResult(intent, TAKE_PICTURE);  //用户点击了从相机获取
                    }else {
                        ActivityCompat.requestPermissions(MyInfoActivity.this,
                                new String[]{Manifest.permission.CAMERA},
                                1);
                    }
                }
            }
        });
    }


    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context,
                    "com.zhongshengnetwork.rightbe.fileprovider", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

    /**从相册获取图片**/
    private void doPickPhotoFromGallery() {
        /*
        PhotoPickerIntent intent = new PhotoPickerIntent(MyInfoActivity.this);
        intent.setPhotoCount(1);
        intent.setShowCamera(true);
        startActivityForResult(intent, CHOOSE_PICTURE);
        */
//        PhotoPicker.builder()
//                .setPhotoCount(1)
//                .setShowCamera(false)
//                .setShowGif(false)
//                .setPreviewEnabled(false)
//                .start(MyInfoActivity.this, CHOOSE_PICTURE);//PhotoPicker.REQUEST_CODE
        EasyPhotos.createAlbum(this, false, GlideEngine.getInstance())
                .start(CHOOSE_PICTURE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
                    cropImage(Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES)+"/image.jpg")));
                    /*
                    //将保存在本地的图片取出并缩小后显示在界面上
                    Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/image.jpg");
                    //Bitmap newBitmap = zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
                    Bitmap newBitmap = CommonUtils.getZoomImage(bitmap,50);
                            //由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
                    bitmap.recycle();
                    //将处理过的图片显示在界面上，并保存到本地
                    //iv_image.setImageBitmap(newBitmap);
                    savePhotoToSDCard(Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()), newBitmap);
                    if (imgType == 0){//背景图
                        uploadBg(newBitmap);
                    }else if (imgType == 1){//头像
                        uploadHeader(newBitmap);
                    }
                    */
                    break;

                case CHOOSE_PICTURE:
                    /*
                    if (data != null){
//                        ArrayList<String> photos =
//                                data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                        ArrayList<String> photos =
                                data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                        cropImage(Uri.fromFile(new File(photos.get(0))));

                    }
                    */
                    if (data != null){
                        ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                        if (resultPhotos != null && resultPhotos.size() > 0){
                            Photo photo = resultPhotos.get(0);
                            cropImage(Uri.fromFile(new File(photo.path)));
                        }
                    }

                    break;

                case CROP_PICTURE:
                    System.out.print("裁剪完毕\n");
                    // 拿到剪切数据
                    if (data != null){
                        Bitmap bmap = data.getParcelableExtra("data");
                        if (bmap != null){
                            if (imgType == 0){//背景图
                                uploadBg(bmap);
                            }else if (imgType == 1){//头像
                                uploadHeader(bmap);
                            }
                        }
                    }

                    break;

                case NICKNAME_REQUSET:
                    adapter.notifyDataSetChanged();
                    Intent mIntent = new Intent(BroadcastDefine.Update_MyInfo);
                    //发送广播
                    sendBroadcast(mIntent);
                    break;

                case SIGN_REQUEST:
                    adapter.notifyDataSetChanged();
                    break;
                case SELECT_LOCATION:
                    adapter.notifyDataSetChanged();
                    break;

                case UCrop.REQUEST_CROP:
                    if (data != null){
                        final Uri resultUri = UCrop.getOutput(data);
                        Bitmap bitmap = BitmapFactory.decodeFile(resultUri.getEncodedPath());
                        if (imgType == 0){//背景图
                            uploadBg(bitmap);
                        }else if (imgType == 1){//头像
                            uploadHeader(bitmap);
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    }

    /** 缩放Bitmap图片 **/
    public Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    /** 为图片创建不同的名称用于保存，避免覆盖 **/
    public static String createFileName() {
        String fileName = "";
        Date date = new Date(System.currentTimeMillis()); // 系统当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        fileName = dateFormat.format(date) + ".jpg";
        return fileName;
    }

    /**Save image to the SD card**/
    public static void savePhotoToSDCard(String path, String photoName,
                                         Bitmap photoBitmap) {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File photoFile = new File(path, photoName); //在指定路径下创建文件
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(photoFile);
                if (photoBitmap != null) {
                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,
                            fileOutputStream)) {
                        fileOutputStream.flush();
                    }
                }
            } catch (FileNotFoundException e) {
                photoFile.delete();
                e.printStackTrace();
            } catch (IOException e) {
                photoFile.delete();
                e.printStackTrace();
            } finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener(){

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.first_button:
                    if (imgType == 3){
                        changeUserInfo(1);
                    }else {
                        doTakePhoto();
                    }

                    break;
                case R.id.second_button:
                    if (imgType == 3){
                        changeUserInfo(2);
                    }else {
                        doPickPhotoFromGallery();
                    }

                    break;
                case R.id.third_button:
                    if (imgType == 3){
                        changeUserInfo(0);
                    }
                    break;

                default:
                    imgType = 0;
                    break;
            }


        }

    };

    //修改头像
    private void changeHeader(){
        new AlertView("设置头像", null, "取消", null,
                new String[]{"拍照", "从相册中选择"},
                this, AlertView.Style.ActionSheet, new OnItemClickListener(){
            public void onItemClick(Object o,int position){
                System.out.print("选择了："+position+"\n");
            }
        }).show();
    }

    //裁剪
    private void cropImage(Uri uri){
        /*
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//可裁剪
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 800);
        intent.putExtra("outputY", 800);
        intent.putExtra("scale", true);
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", true);//若为false则表示不返回数据
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, CROP_PICTURE);
        */
        UCrop.of(uri, Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"imageout.jpg")))
                .withAspectRatio(1, 1)
                .withMaxResultSize(600, 600)
                .start(MyInfoActivity.this);
    }

    //修改个人信息
    private void changeUserInfo(final int sexType){
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put(APIKey.sexKey,sexType+"");
        HttpsUtils.changeuserinfoDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    CustomApplication.loginModel.setSex(sexType+"");
                    LogindbService.saveOrUpdateLogindbMode(CustomApplication.loginModel);
                    adapter.notifyDataSetChanged();
                }else {
                    CustomApplication.showTip(commonModel,MyInfoActivity.this);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    //上传背景图片
    private void uploadBg(final Bitmap bitmap){
        KyLoadingBuilder dialog = new KyLoadingBuilder(MyInfoActivity.this);
        dialog.setIcon(R.drawable.loading04);
        dialog.setText("正在上传...");
        dialog.setOutsideTouchable(false);//点击空白区域是否关闭
        dialog.setBackTouchable(true);//按返回键是否关闭
        dialog.show();

        //将保存在本地的图片取出并缩小后显示在界面上
        //final Bitmap bitmap = zoomBitmap(ibitmap, ibitmap.getWidth() / SCALE, ibitmap.getHeight() / SCALE);
        //由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.getQiniuTokenDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")) {
                    final QiniuModel model = GsonTools.getQiniuModel(data);
                    final String name = System.currentTimeMillis()+"1"+".jpg";
                    CommonUtils.uploadBytesToQiniu(model.getUploadtoken(), model.getUploadurl(), name, CommonUtils.bitmapToBytes(bitmap), new QiniuCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            System.out.print("上传成功："+data+"\n");
                            if (data != null){
                                final String bg = data;
                                final Map<String,String> map = new HashMap<String, String>();
                                map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                                map.put(APIKey.backgroundKey,data);
                                HttpsUtils.changeuserinfoDo(map, new HttpCallBack() {
                                    @Override
                                    public void onSuccess(String data) {
                                        dialog.dismiss();
                                        CommonModel commonModel = GsonTools.getCommonModel(data);
                                        if (commonModel.getFlag().equals("1")){
                                            CustomApplication.loginModel.setBackground(bg);
                                            LogindbService.saveOrUpdateLogindbMode(CustomApplication.loginModel);
                                            adapter.notifyDataSetChanged();
                                        }else {
                                            ToastUtil.show(MyInfoActivity.this,"上传失败");
                                        }
                                    }

                                    @Override
                                    public void onError(String msg) {
                                        dialog.dismiss();
                                        ToastUtil.show(MyInfoActivity.this,"上传失败");
                                    }
                                });
                            }else {
                                dialog.dismiss();
                                ToastUtil.show(MyInfoActivity.this,"上传失败");
                            }
                        }

                        @Override
                        public void onModelSuccess(QiniuUploadModel data) {

                        }

                        @Override
                        public void onError(String msg) {
                            dialog.dismiss();
                            ToastUtil.show(MyInfoActivity.this,"上传失败");
                        }
                    });
                }else {
                    dialog.dismiss();
                    CustomApplication.showTip(commonModel,MyInfoActivity.this);
                }
            }

            @Override
            public void onError(String msg) {
                dialog.dismiss();
                ToastUtil.show(MyInfoActivity.this,"无法上传");
            }
        });
    }

    //上传头像
    private void uploadHeader(final Bitmap bitmap){
        final Bitmap smallBitmap = ThumbnailUtils.extractThumbnail(bitmap,100,100);
        KyLoadingBuilder dialog = new KyLoadingBuilder(MyInfoActivity.this);
        dialog.setIcon(R.drawable.loading04);
        dialog.setText("正在上传...");
        dialog.setOutsideTouchable(false);//点击空白区域是否关闭
        dialog.setBackTouchable(true);//按返回键是否关闭
        dialog.show();
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.getQiniuTokenDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    final QiniuModel model = GsonTools.getQiniuModel(data);
                    long time = System.currentTimeMillis();
                    final String name = time+"1"+".jpg";
                    final String sname = time+"1s"+".jpg";
                    //上传大图
                    CommonUtils.uploadBytesToQiniu(model.getUploadtoken(), model.getUploadurl(), name, CommonUtils.bitmapToBytes(bitmap), new QiniuCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            System.out.print("大图上传成功："+data+"\n");
                            final String bUrl = data;
                            if (data != null){
                                //上传小图
                                CommonUtils.uploadBytesToQiniu(model.getUploadtoken(), model.getUploadurl(), sname, CommonUtils.bitmapToBytes(smallBitmap), new QiniuCallBack() {
                                    @Override
                                    public void onSuccess(String data) {
                                        System.out.print("小图上传成功："+data+"\n");
                                        if (data != null){
                                            final String sUrl = data;
                                            //上传到服务器
                                            final Map<String,String> map = new HashMap<String, String>();
                                            map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                                            map.put(APIKey.headerKey,bUrl);
                                            map.put(APIKey.thumbheaderKey,sUrl);
                                            HttpsUtils.changeuserinfoDo(map, new HttpCallBack() {
                                                @Override
                                                public void onSuccess(String data) {
                                                    dialog.dismiss();
                                                    CommonModel commonModel = GsonTools.getCommonModel(data);
                                                    if (commonModel.getFlag().equals("1")){
                                                        CustomApplication.loginModel.setHeader(bUrl);
                                                        CustomApplication.loginModel.setThumbheader(sUrl);
                                                        LogindbService.saveOrUpdateLogindbMode(CustomApplication.loginModel);
                                                        adapter.notifyDataSetChanged();
                                                        Intent mIntent = new Intent(BroadcastDefine.Update_MyInfo);
                                                        //发送广播
                                                        sendBroadcast(mIntent);
                                                    }else {
                                                        ToastUtil.show(MyInfoActivity.this,"上传失败");
                                                    }
                                                }

                                                @Override
                                                public void onError(String msg) {
                                                    dialog.dismiss();
                                                    ToastUtil.show(MyInfoActivity.this,"上传失败");
                                                }
                                            });
                                            //上传到服务器
                                        }else {
                                            dialog.dismiss();
                                            ToastUtil.show(MyInfoActivity.this,"上传失败");
                                        }
                                    }

                                    @Override
                                    public void onModelSuccess(QiniuUploadModel data) {

                                    }

                                    @Override
                                    public void onError(String msg) {
                                        dialog.dismiss();
                                        ToastUtil.show(MyInfoActivity.this,"上传失败");
                                    }
                                });
                                //上传小图
                            }else {
                                dialog.dismiss();
                                ToastUtil.show(MyInfoActivity.this,"上传失败");
                            }
                        }

                        @Override
                        public void onModelSuccess(QiniuUploadModel data) {

                        }

                        @Override
                        public void onError(String msg) {
                            dialog.dismiss();
                            ToastUtil.show(MyInfoActivity.this,"上传失败");
                        }
                    });
                    //上传图片
                }else {
                    dialog.dismiss();
                    CustomApplication.showTip(commonModel,MyInfoActivity.this);
                }
            }

            @Override
            public void onError(String msg) {
                dialog.dismiss();
                ToastUtil.show(MyInfoActivity.this,"上传失败");
            }
        });
    }

}
